/**
 * 
 */
package com.tmc.web.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.tmc.bean.common.ContextInfo;
import com.tmc.service.common.LoginServiceImpl;

public class MyInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private LoginServiceImpl login;

	/**
	 * 最后执行，可用于释放资源
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 显示视图前执行
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * Controller之前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		
		String url = request.getRequestURI();
		if (url.contains("login") || url.contains("register") || url.contains("/js/") || url.contains("/css/") || url.contains("/image/")
				|| url.contains("/img/") || url.contains("/lib/") || url.contains("/static/") || url.contains("/flightSearch/") || url.contains("/ctrip")
				|| url.contains("json") || url.contains("/api/")) {
			super.preHandle(request, response, handler);
			return true;
		}
		final Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (final Cookie cookie : cookies) {
				final String sName = cookie.getName();
				if (sName.equals("token")) {
					// 获得存储在 Cookies 中的token
					final String token = cookie.getValue();
					ContextInfo context = login.getContextInfoByToken(token);
					if (context != null) {
						request.getSession().setAttribute("token", token);
						super.preHandle(request, response, handler);
						return true;
					}
				}
			}
		}
		response.sendRedirect(request.getContextPath() + "/login-page");
		return false;
	}
}
